package com.liangtian.mdm.system.ugroup.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.liangtian.mdm.base.dao.JdbcDao;
import com.liangtian.mdm.base.exception.TransactionalException;
import com.liangtian.mdm.base.utils.ShiroSessionUtils;
import com.liangtian.mdm.dm.common.constant.TableConst;
import com.liangtian.mdm.dm.common.enums.Flag;
import com.liangtian.mdm.dm.jsp.dao.JspActionDao;
import com.liangtian.mdm.system.ugroup.dao.SysUgroupDao;
import com.liangtian.mdm.system.ugroup.dao.SysUgroupUserDao;
import com.liangtian.mdm.system.ugroup.model.SysUgroup;
import com.liangtian.mdm.system.ugroup.model.SysUgroupUser;
import com.liangtian.mdm.system.ugroup.service.SysUgroupService;
import com.liangtian.mdm.system.user.model.SysUser;
import com.liangtian.mdm.util.ConstantBean;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>Encoding    :  UTF-8</p>
 * <p>Package Name: com.liangtian.mdm.system.ugroup.service.impl</p>
 * <p>Project Name: chccig-dm </p>
 * <p>Copyright   :  Copyright(c) 2016 石化盈科信息技术有限责任公司 </p>
 * <p>Created Time: 2016-08-30 </p>
 * <p>Description : 用户实现服务接口</p>
 *
 * @author : byr
 * @version :  1.0
 */
@Service
public class SysUgroupServiceImpl implements SysUgroupService {

    private static final Logger logger = LoggerFactory.getLogger(SysUgroupServiceImpl.class);

    //注入用户dao层接口
    @Autowired
    SysUgroupDao sysUgroupDao;

    @Autowired
    JspActionDao jspActionDao;

    @Autowired
    private JdbcDao jdbcDao;

    @Autowired
    SysUgroupUserDao sysUgroupUserDao;

    ////@Value("${ConstantBean.CURRENT_SESSION_USER}")
    //private String ConstantBean.CURRENT_SESSION_USER;


    /**
     * @param param
     * @return 分页条件下的
     * @desc 获取全部用户组信息(包含查询)
     * @params参数详情 pageNum 总页数
     * @params参数详情 length 每页显示条数
     * @params参数详情 start 起始条数
     * @params参数详情 draw 请求次数
     */
    @Override
    public PageInfo queryUgroupList(Map<String, Object> param) {

        PageInfo<List<Map>> pageInfo = null;
        try {
            List<String> lst = columnList(param);
            String cols = listToString(lst);
            param.put("columns", cols.subSequence(0, cols.length() - 1));
            param.put("tableName", "SYS_UGROUP");
            //拼接查询条件
            Object filter = param.get("filter");  //Mapper直接使用filter.key=filter.value ？
            if (filter != null && !"".equals(filter)) {
                JSONObject json = JSON.parseObject(filter.toString());
                StringBuilder where = new StringBuilder();
                for (String cond : json.keySet()) {
                    //if(param.containsKey(cond)) continue; //与初始条件重复？
                    param.put(cond, Flag.toValue(json.get(cond), cond));
                    where.append(" and ").append(cond).append(" like'%'||#{").append(cond).append("}||'%' ");
                }
                param.put("where", where);
            }

            Object pNo = param.get("pageNum");
            int pageNum, pageSize;
            // export
            if (pNo != null && !"NaN".equals(pNo)) {
                pageNum = Integer.parseInt(pNo.toString());//页码
            } else {
                pageNum = 1;
            }
            //pageSize=0时不分页
            pageSize = Integer.parseInt(param.get("limit").toString());//每页条数
            PageHelper.startPage(pageNum, pageSize);//分页
            List<Map<String, Object>> list = jspActionDao.queryUserList(param);
            pageInfo = new PageInfo(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pageInfo;
    }


    /**
     * @param param
     * @return list
     * @desc 获取用户组表列信息
     */
    public List<String> columnList(Map<String, Object> param) {
        List<Map<String, Object>> columsList = null;
        Map<String, Object> condMap = new HashMap<>();
        String operType = String.valueOf(param.get("operType"));
        if ("sys_ugroup".equals(operType))
            condMap.put("tableName", "SYS_UGROUP");
        columsList = sysUgroupDao.selectColums(condMap);
        List<String> lst = (List<String>) resultSwitch(columsList).get("colNameList");
        return lst;
    }

    /**
     * @param List<Map<String, Object>> lst
     * @return list
     * @desc list包含map转换为list
     */
    public Map<String, Object> resultSwitch(List<Map<String, Object>> lst) {
        Map<String, Object> result_Map = new HashMap<>();
        List<String> columnList = new ArrayList<String>();
        for (Map map : lst) {
            for (Object key : map.keySet()) {
                if ("columnName".equals(key + "")) {
                    columnList.add(map.get(key) + "");
                }
            }
        }
        result_Map.put("colNameList", columnList);
        return result_Map;
    }

    /**
     * @param list
     * @return string
     * @desc list转换为string
     */
    public String listToString(List<String> list) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < list.size(); i++) {
            sb.append(list.get(i)).append(",");
        }
        return sb.toString();
    }

    /**
     * @param Map
     * @des 新增用户组
     */
    @Override
    public boolean insertUgroup(Map<String, Object> param) {
        //新增用户组
        String tableName = param.get("tableName").toString();
        StringBuilder sqlHeader = new StringBuilder();
        StringBuilder sqlValues = new StringBuilder();
        sqlHeader.append("insert into ").append(tableName).append("(");
        sqlValues.append("values(");
        List<String> colist = columnList(param);
        SysUser user = null;
        for (int i = 0; i < colist.size(); i++) {
            if (i == colist.size() - 1)
                sqlHeader.append(colist.get(i)).append(")");
            else
                sqlHeader.append(colist.get(i)).append(",");
            if (colist.get(i).equals("GROUPID"))
                sqlValues.append(tableName).append(TableConst.SEQUENCESUFFIX).append(".nextval,");
            else if (colist.get(i).equals("CREATETIME"))
                sqlValues.append("sysdate,");
            else if (colist.get(i).equals("CREATORID")) {
                user = ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER);
                sqlValues.append("'").append(user.getUserId()).append("',");
            } else {
                String value = (String) param.get(colist.get(i).toLowerCase());
                if (value != null) {
                    sqlValues.append("'").append(value).append("',");
                } else {
                    sqlValues.append(" null,");
                }
            }
        }
        String str = (String) sqlValues.subSequence(0, sqlValues.length() - 1);
        String sql = sqlHeader.append(str).append(")").toString();
        return jdbcDao.executeSql(sql);
    }


    /**
     * @param Button
     * @des 编辑用户组
     */
    @Override
    public boolean updateUgroup(SysUgroup sysUgroup) throws TransactionalException {
        boolean flag = false;
        try {
            sysUgroupDao.updateGroup(sysUgroup);
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * @param Map
     * @desc 批量删除用户组信息
     * @params参数详情 idsList 用户id
     */
    @Override
    public boolean batchDeleteUgroup(Map<String, Object> params) throws TransactionalException {
        boolean flag = false;
        //删除用户
        try {
            sysUgroupDao.batchDeleteUgroup(params);
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * @param Map
     * @return 分页条件下的
     * @desc 获取用户组用户信息
     * @params参数详情 pageNum 总页数
     * @params参数详情 length 每页显示条数
     * @params参数详情 start 起始条数
     * @params参数详情 draw 请求次数
     */
    @Override
    public PageInfo selectUserList(Map<String, Object> param) {
        PageInfo<List<SysUgroupUser>> pageInfo = null;
        try {
            Object pNo = param.get("pageNum");
            int pageNum, pageSize;
            // export
            if (pNo != null && !"NaN".equals(pNo)) {
                pageNum = Integer.parseInt(pNo.toString());// 页码
            } else {
                pageNum = 1;
            }
            // pageSize=0时不分页
            pageSize = Integer.parseInt(param.get("limit").toString());// 模型定义页面要显示数据条数
            // 例如
            // 10,20,50,100
            PageHelper.startPage(pageNum, pageSize);// 开始分页标志（当前页，显示条数）

            List<SysUgroupUser> groupUserList = sysUgroupUserDao.queryUsersList(param);
            pageInfo = new PageInfo(groupUserList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pageInfo;
    }


    /**
     * @param Map
     * @des 新增用户组用户
     */
    @Override
    public boolean insertUgroupUser(Map<String, Object> param) {
        boolean flag = false;
        String[] ids = (String[]) param.get("ids");
        String ugroupid = (String) param.get("ugroupid");
        List<SysUgroupUser> userList = new ArrayList<SysUgroupUser>();
        for (int i = 0; i < ids.length; i++) {
            SysUgroupUser sysUgroupUser = new SysUgroupUser();
            sysUgroupUser.setGroupId(ugroupid);
            String str = ids[i];
            sysUgroupUser.setUserId(str);
            userList.add(sysUgroupUser);
        }

        try {
            sysUgroupUserDao.insertUgroupUserBatch(userList);
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }


    /**
     * @param params
     * @desc 批量删除用户组用户信息
     * @params参数详情 idsList 用户组id
     */
    @Override
    public boolean deleteUgroupUserBatch(Map<String, Object> params)
            throws TransactionalException {
        boolean flag = false;
        try {
            sysUgroupUserDao.deleteUgroupUserBatch(params);
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }


    /**
     * @param groupid
     * @desc 根据ID查询用户组
     */
    @Override
    public SysUgroup queryOne(String groupid) {
        SysUgroup sysUgroup = sysUgroupDao.queryOne(groupid);
        return sysUgroup;
    }


    @Override
    public PageInfo queryAllUgroupList(Map<String, Object> map) {
        PageInfo<Map<String, Object>> pageInfo = null;
        try {
            Object pNo = map.get("pageNum");
            int pageNum, pageSize;
            // export
            if (pNo != null && !"NaN".equals(pNo)) {
                pageNum = Integer.parseInt(pNo.toString());// 页码
            } else {
                pageNum = 1;
            }
            // pageSize=0时不分页
            pageSize = Integer.parseInt(map.get("limit").toString());// 模型定义页面要显示数据条数
            // 例如
            // 10,20,50,100
            PageHelper.startPage(pageNum, pageSize);// 开始分页标志（当前页，显示条数）

            List<Map<String, Object>> userMapList = sysUgroupDao.queryAllUGroup(map);
            pageInfo = new PageInfo<Map<String, Object>>(userMapList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pageInfo;
    }


}
